package cn.com.openportal.ffw.common.utils;

import cn.com.openportal.ffw.common.annotation.DataFilter;
import cn.com.openportal.ffw.modules.sys.entity.SysUserEntity;
import cn.com.openportal.ffw.modules.sys.service.SysDeptService;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author LeeSon QQ & WX:25901875
 * @version V1.0
 * @Package cn.com.openportal.ffw.common.utils
 * @create 2020-01-17 21:00
 * @Copyright © 2019 LeeSon QQ & WX:25901875
 */
@Component
public class SQLFilterUtils {
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 获取数据过滤的SQL
     */
    public String getSQLFilter(SysUserEntity user, JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);
        //获取表的别名
        String tableAlias = dataFilter.tableAlias();
        if (StringUtils.isNotBlank(tableAlias)) {
            tableAlias += ".";
        }

        //部门ID列表
        Set<Long> deptIdList = new HashSet<>();

        //添加本级部门
        deptIdList.add(user.getDeptId());

        //用户子部门ID列表
        if (dataFilter.subDept()) {
            List<Long> subDeptIdList = sysDeptService.getSubDeptIdList(user.getDeptId());
            deptIdList.addAll(subDeptIdList);
        }

        StringBuilder sqlFilter = new StringBuilder();
        sqlFilter.append(" (");

        if (deptIdList.size() > 0) {
            sqlFilter.append(tableAlias).append(dataFilter.deptId()).append(" in(").append(StringUtils.join(deptIdList, ",")).append(")");
        }

        //只能查询本人数据
        if (dataFilter.user()) {
            if (deptIdList.size() > 0) {
                sqlFilter.append(" and ");
            }
            sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getUserId());
        }

        sqlFilter.append(")");

        if (sqlFilter.toString().trim().equals("()")) {
            return null;
        }

        return sqlFilter.toString();
    }
}
